package com.llkj.youdaocar.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.llkj.youdaocar.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;

public class Utils {
    public static String path = null;
    public static final String IMAGE_UNSPECIFIED = "image/*";
    public static final int PHOTORESOULT = 3;// 结果
    public static final int REQUEST_CODE_CAMERA = 7001;
    public static final int REQUEST_CODE_LOCAL = 19;
    public static List<Activity> stackActivity = new ArrayList<Activity>();

    public static void addActivity(Activity activity) {
        stackActivity.add(activity);
    }

    public static void closeActivity() {
        try {
            for (int i = 0; i < stackActivity.size(); i++) {
                if (!stackActivity.get(i).isFinishing()) {
                    stackActivity.get(i).finish();
                }
            }
            stackActivity.clear();
        } catch (Exception e) {
        }
    }
    // 获取当前版本号码和名称
    public static PackageInfo getCurrentVersion(Context context) {
        PackageInfo info = null;
        try {
            info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return info;
    }
    /**
     * 获取app的存储目录
     * <p/>
     * 一般情况下是这样的/storage/emulated/0/Android/data/包名/
     *
     * @param context
     * @return
     */
    public static String getAppDir(Context context) {
        return (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState()) ? (Environment
                .getExternalStorageDirectory().getPath() + "/Android/data/")
                : (context.getCacheDir().getPath()))
                + context.getPackageName() + "/img/";
    }

    /**
     * 获取app的存储目录
     * <p/>
     * 一般情况下是这样的/storage/emulated/0/Android/data/包名/
     *
     * @param context
     * @return
     */
    public static String getAppBooksDir(Context context) {
        return (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState()) ? (Environment
                .getExternalStorageDirectory().getPath() + "/Android/data/")
                : (context.getCacheDir().getPath()))
                + context.getPackageName() + "/book/";
    }

    /**
     * 开启一个系统页面来裁剪传进来的照片
     *
     * @param uri uri 需要裁剪的照片的URI值
     */
    public static void startPhotoZoom(Activity activity, Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        activity.startActivityForResult(intent, PHOTORESOULT);
    }

    /**
     * 开启一个系统页面来裁剪传进来的照片
     *
     * @param uri uri 需要裁剪的照片的URI值
     */
    public static void startPhotoZoom(Activity activity, Uri uri, int aspectX, int aspectY) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        activity.startActivityForResult(intent, PHOTORESOULT);
    }

    /**
     * 从图库获取图片
     */
    public static void selectPicFromLocal(Activity activity) {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(
                    Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        activity.startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param pxValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @param spValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取设备ID
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        TelephonyManager manager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (!TextUtils.isEmpty(manager.getDeviceId())) {
            return manager.getDeviceId();
        } else {
            final String tmDevice, tmSerial, tmPhone, androidId;

            tmDevice = "" + manager.getDeviceId();

            tmSerial = "" + manager.getSimSerialNumber();

            androidId = ""
                    + android.provider.Settings.Secure.getString(
                    context.getContentResolver(),
                    android.provider.Settings.Secure.ANDROID_ID);

            UUID deviceUuid = new UUID(androidId.hashCode(),
                    ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());

            String uniqueId = deviceUuid + "";
            return uniqueId;
        }
    }

    /**
     * 获取应用AppKey
     *
     * @return
     */
    public static String getAppKey(Context context) {
        ApplicationInfo applicationInfo = null;
        String appKey = null;
        try {
            applicationInfo = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            appKey = applicationInfo.metaData.getString("app_key");
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return appKey;
    }

    public static String getAppSecret(Context context) {
        ApplicationInfo applicationInfo = null;
        String appSecret = null;
        try {
            applicationInfo = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            appSecret = applicationInfo.metaData.getString("app_secret");
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return appSecret;
    }

    public static boolean hasSDCard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }

    /**
     * bitmap转成byte数组
     *
     * @param avatar
     * @return
     */
    public static byte[] Bitmap2Bytes(Bitmap avatar) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        avatar.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();

    }

    /**
     * 此方法用于现场互动界面,格式固定. e.g.day=18,mounth=九月.
     *
     * @param day
     * @param month
     * @return
     */
    public static boolean isToday(String day, String month) {
        Calendar c = Calendar.getInstance();
        int m = c.get(Calendar.MONTH);
        int d = c.get(Calendar.DAY_OF_MONTH);
        if (!TextUtils.isEmpty(day) && !TextUtils.isEmpty(month)) {
            if (month.equals(Num2Hanzi(m)) && String.valueOf(d).equals(day)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 转化月份.数字转汉字
     *
     * @param num
     * @return
     */
    public static String Num2Hanzi(int num) {
        StringBuffer sb = new StringBuffer();
        String[] strings = new String[]{"一", "二", "三", "四", "五", "六", "七",
                "八", "九", "十", "十一", "十二"};
        return sb.append(strings[num]).append("月") + "";
    }

    /**
     * 转化月份.汉字转数字
     *
     * @param hanzi
     * @return
     */
    public static int Hanzi2Num(String hanzi) {
        int num = 0;
        int[] numbers = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
        String[] strings = new String[]{"一月", "二月", "三月", "四月", "五月", "六月",
                "七月", "八月", "九月", "十月", "十一月", "十二月"};
        for (int i = 0; i < strings.length; i++) {

            if (hanzi.equals(strings[i])) {
                num = numbers[i];
            }
        }
        return num;
    }

    /**
     * 获取手机上的联系人电话.
     *
     * @return
     */
    public static void getContacts(Context context,
                                   final IContactCallback callback) {
        final Context ctx = context;
        new Thread(new Runnable() {
            @Override
            public void run() {

                StringBuffer sb = new StringBuffer();
                Cursor cursor = ctx.getContentResolver().query(
                        ContactsContract.Contacts.CONTENT_URI, null, null,
                        null, null);
                if (cursor != null) {
                    while (cursor.moveToNext()) {

                        String contactId = cursor.getString(cursor
                                .getColumnIndex(ContactsContract.Contacts._ID));
                        String displayName = cursor.getString(cursor
                                .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        int numberCount = cursor.getInt(cursor
                                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                        if (numberCount > 0) {
                            Cursor c = ctx
                                    .getContentResolver()
                                    .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                            null,
                                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                                    + "=" + contactId, null,
                                            null);
                            if (c != null) {
                                while (c.moveToNext()) {
                                    String number = c.getString(c
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                    if (number.contains(" ")) {
                                        number = number.replace(" ", "");
                                    }
                                    if (number.contains("-")) {
                                        number = number.replace("-", "");
                                    }
                                    // 截取后11位.针对前面有+86前缀的.
                                    if (number.length() > 11) {
                                        number = number.subSequence(
                                                number.length() - 11,
                                                number.length())
                                                + "";
                                    }

                                    sb.append(number);
                                    sb.append(",");
                                }
                                c.close();
                                c = null;
                            }
                        }
                    }
                    cursor.close();
                    cursor = null;
                }
                if ((sb + "").endsWith(",")) {
                    sb.delete(sb.length() - 1, sb.length());
                }
                callback.callback(sb + "");
            }

        }).start();
    }

    public interface IContactCallback {
        void callback(String string);
    }

    public static boolean hasFroyo() {
        return Build.VERSION.SDK_INT >= VERSION_CODES.FROYO;

    }

    public static boolean hasGingerbread() {
        return Build.VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD;
    }

    public static boolean hasHoneycomb() {
        return Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
    }

    public static boolean hasHoneycombMR1() {
        return Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR1;
    }

    public static boolean hasJellyBean() {
        return Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN;
    }

    public static boolean hasKitKat() {
        return Build.VERSION.SDK_INT >= 19;
    }

    public static List<Size> getResolutionList(Camera camera) {
        Parameters parameters = camera.getParameters();
        List<Size> previewSizes = parameters.getSupportedPreviewSizes();
        return previewSizes;
    }

    public static class ResolutionComparator implements Comparator<Size> {

        @Override
        public int compare(Size lhs, Size rhs) {
            if (lhs.height != rhs.height)
                return lhs.height - rhs.height;
            else
                return lhs.width - rhs.width;
        }

    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean flymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    /**
     * 设置状态栏字体图标为深色，需要MIUIV6以上
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean mIUISetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    public static void setStatusBarFontColor(Window window, boolean dark) {
        boolean isTrue = flymeSetStatusBarLightMode(window, dark);
        if (!isTrue) {
            isTrue = mIUISetStatusBarLightMode(window, dark);
        }
        if (!isTrue && Build.VERSION.SDK_INT >= VERSION_CODES.M) {
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        if (!isTrue && Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            // 部分机型的statusbar会有半透明的黑色背景
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(Color.TRANSPARENT);// SDK21
        }
    }

    @TargetApi(19)
    public static void setTranslucentStatus(Window win, boolean on) {
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public static SystemBarTintManager setStatusBarFontColor(Activity activity, boolean dark) {
        Window window = activity.getWindow();
        setTranslucentStatus(window, true);
        SystemBarTintManager tintManager = new SystemBarTintManager(activity);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(R.color.white);//通知栏所需颜色

        boolean isTrue = flymeSetStatusBarLightMode(window, dark);
        if (!isTrue) {
            isTrue = mIUISetStatusBarLightMode(window, dark);
        }

        if (isTrue) {
            return tintManager;
        }

        if (!isTrue && Build.VERSION.SDK_INT >= VERSION_CODES.M) {
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            tintManager.setStatusBarTintResource(R.color.white);//通知栏所需颜色
        } else if (!isTrue && Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            //部分机型的statusbar会有半透明的黑色背景
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(ContextCompat.getColor(activity,R.color.white));// SDK21
            //设置状态栏的颜色
            // window.setStatusBarColor(activity.getResources().getColor(colorResId));
            //设置底部的颜色
            //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
//            tintManager.setStatusBarTintResource(R.color.blackTransparent);//通知栏所需颜色
        } else if (!isTrue && Build.VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            tintManager.setStatusBarTintResource(ContextCompat.getColor(activity,R.color.white));//通知栏所需颜色
        }
        return tintManager;
    }

    public static boolean setsetStatusBarFontColor5(SystemBarTintManager tintManager,Activity activity,int color){
        if (Build.VERSION.SDK_INT < VERSION_CODES.M &&Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            window.setStatusBarColor(Color.TRANSPARENT);// SDK21
            tintManager.setStatusBarTintResource(color);//通知栏所需颜色
            return true;
        }
        return false;
    }
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

}
